package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author heixiaolv.com
 * @date 2021/12/1 22:38
 */

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")//从属性文件读取输出目录的路径
    private String outPutPath;

    public void add(Setmeal setmeal, Integer[] checkgroupids) {
        setmealDao.add(setmeal);

        Integer setmealId = setmeal.getId();

        String fileName = setmeal.getImg();
        //将图片名称保存到Redis
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, fileName);

        if (checkgroupids != null && checkgroupids.length > 0) {
            this.setSetmealAndCheckgroup(setmealId, checkgroupids);
        }

        //新增套餐后需要重新生成静态页面
        generateMobileStaticHtml();
    }

    //生成静态页面
    public void generateMobileStaticHtml() {
        List<Setmeal> setmealList = setmealDao.findAll();

        Map<String, Object> map = null;
        if (setmealList != null && !setmealList.isEmpty()) {
            //生成套餐列表静态页面
            generateMobileSetmealListHtml(setmealList);
            //生成套餐详情静态页面（多个）
            generateMobileSetmealDetailHtml(setmealList);
        }
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> setmealList){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("setmealList",setmealList);
        generateHtml("mobile_setmeal.ftl","m_setmeal.html", map);
    }

    //生成套餐详情静态页面（多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList){
        Map<String, Object> map = null;
        for (Setmeal setmeal : setmealList) {
            map = new HashMap<String, Object>();
            map.put("setmeal", setmealDao.findById(setmeal.getId()));
            generateHtml("mobile_setmeal_detail.ftl",
                    "setmeal_detail_"+setmeal.getId()+".html",map);
        }
    }

    //动态生成静态页面
    public void generateHtml(String templateName, String htmlPageName, Map<String, Object> map) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            // 加载模版文件
            Template template = configuration.getTemplate(templateName);
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            //输出文件
            template.process(map, out);
            //关闭连接
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage, pageSize);

        Page<Setmeal> page = setmealDao.selectByCondition(queryString);

        List<Setmeal> rows = page.getResult();
        long total = page.getTotal();

        return new PageResult(total, rows);
    }

    //查询所有套餐信息
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    //根据套餐id查询检查组详情信息
    public Setmeal findById(int id) {
        return setmealDao.findById(id);
    }

    //根据id查询简单的套餐信息
    public Setmeal findSetmealById(int id) {
        return setmealDao.findSetmealById(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    public void setSetmealAndCheckgroup(Integer setmealId, Integer[] checkgroupids) {

        Map<String, Integer> map = null;

        for (Integer checkgroupid : checkgroupids) {
            map = new HashMap<>();

            map.put("setmealId", setmealId);
            map.put("checkgroupId", checkgroupid);

            setmealDao.setSetmealAndCheckgroup(map);

            System.out.println(map);
        }
    }

}
